package com.atcd.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component //可以扫描到
public class MyLb implements LoadBalance{

    //CAS
    private AtomicInteger atomicInteger= new AtomicInteger(0);


    //自旋锁，保证原子性

    /**
     * next:第几次访问
     * @return
     */
    public final  int getAndIncrement(){
        int current;
        int next;
        do{
            current=this.atomicInteger.get();
            next=current>=Integer.MAX_VALUE?0:current+1;
        }while (!this.atomicInteger.compareAndSet(current,next));
        System.out.println("*****************第几次访问, 次数next: "+next);
        return next;
    }


    //轮训算法
    @Override
    public ServiceInstance instance(List<ServiceInstance> serviceInstances) {

        //负载均衡 1%2(机器的数量) ==1 对应下标 1机器
         //       2%2==0  对应 0机器
         //           ......
      int index=  getAndIncrement() % serviceInstances.size();
           //根据坐标选择哪个机器的实例
        return serviceInstances.get(index);
    }

}

